package com.jht.bletool.util;

import android.bluetooth.BluetoothGattCharacteristic;
import android.content.Context;
import android.util.Log;

import com.jht.bletool.APP;
import com.jht.bletool.characteristic.TranslateData;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import dalvik.system.DexFile;
import dalvik.system.PathClassLoader;

//查找 解析数据的类
public final class SelectParseClass {
    private static final String TAG = "SelectParseClass";
    public static Map<String,Class<?>> map = scan(APP.getAppContext(),"com.jht.bletool.characteristic");


    public static TranslateData getTranslateDataInstance(BluetoothGattCharacteristic characteristic){
        String uuid = characteristic.getUuid().toString();
        Class<?> aClass = map.get(uuid);
        if (aClass == null){
            return null;
        }
        try {
            Constructor<?> constructor = aClass.getConstructor(BluetoothGattCharacteristic.class);
            TranslateData o = (TranslateData)constructor.newInstance(characteristic);
            return o;
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
            Log.e(TAG, "getTranslateDataInstance: ");
            return null;
        } catch (IllegalAccessException | InstantiationException | InvocationTargetException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static Map<String,Class<?>> scan(Context ctx, String entityPackage) {

        Map<String,Class<?>> map = new HashMap<>();
        try {
            PathClassLoader classLoader = (PathClassLoader) Thread.currentThread().getContextClassLoader();

            DexFile dex = new DexFile(ctx.getPackageResourcePath());
            Enumeration<String> entries = dex.entries();
            while (entries.hasMoreElements()) {
                String entryName = entries.nextElement();
                if (entryName.contains(entityPackage)) {
                    Class<?> entryClass = Class.forName(entryName, true,classLoader);
                    //DatabaseTable annotation = entryClass.getAnnotation(DatabaseTable.class);
//                    MyUUID annotation = entryClass.getAnnotation(MyUUID.class);
//                    if (annotation != null) {
//                        map.put(annotation.uuid(),entryClass);
//                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }
}
